//
// Created by Bili_TianX_Computer on 2021/7/10.
//

#ifndef SUPERMARKETMANAGESYSTEM_PRODUCTDATAMANAGER_H
#define SUPERMARKETMANAGESYSTEM_PRODUCTDATAMANAGER_H

#include <QList>
#include <QIODevice>
#include <QFile>
#include <QJsonDocument>
#include <QJsonArray>
#include <QDebug>

#include "Product.h"

static QList<Product> *productList;


static void loadProductList()
{
    productList = new QList<Product>;
    QFile file("product.json");
    if (!file.exists() || !file.open(QIODevice::ReadOnly)) return;
    auto obj = QJsonDocument::fromJson(file.readAll()).array();
    for (auto product: obj) productList->append(Product(product.toObject()));
    file.close();
}

static QList<Product> *getProductList()
{
    if (productList == nullptr) loadProductList();
    return productList;
}

static void addProductToList(const Product &product)
{
    getProductList()->append(product);
}

static Product *queryProductByName(const QString &name)
{
    for (Product &p: *getProductList())
    {
        if (p.name == name)
            return &p;
    }
    return nullptr;
}

static void saveProductList()
{
    if (getProductList() == nullptr) return;
    QFile file("product.json");
    if (!file.open(QIODevice::WriteOnly)) return;
    QJsonArray array;
    for (auto &product: *getProductList()) array.append(product.toJsonObject());
    file.write(QJsonDocument(array).toJson());
    file.close();
}

#endif //SUPERMARKETMANAGESYSTEM_PRODUCTDATAMANAGER_H
